<?php

namespace App\Admin\Models;

use App\Admin\Models\BaseModel;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use Encore\Admin\Facades\Admin;
use App\Services\Store;
use App\Services\Common;
use DB;

class StoreMemberCards extends BaseModel
{   
    //指定主键
    protected $primaryKey = 'smcId';
    
    public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

		///////获取数据//////////////////////////////////////////////////////////////////////////////////////
		$sId = Admin::user()->sId;

		$url = $this->host."/storeMemberCards/getList?page={$page}&perPage={$perPage}&scKey={$sId}";
//		print_r($url);exit;
		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);
		
		
		////////获取数据/////////////////////////////////////////////////////////////////////////////////////

		$total = $data['count'];
		
        extract($data['data']);

        $tags = static::hydrate($data['data']);

        $paginator = new LengthAwarePaginator($tags, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }
    
    /**
     * Add a basic where clause to the query.
     *
     * @param  string|array|\Closure  $column
     * @param  mixed   $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and'){
    	// http://localhost:96/admin/remark/remarkTag?rtcId=1
    	// $column rtcId
    	// $operator 1
    	// $value null
    	// $boolean and
    	return $this;
    }
    
    // 获取单项数据展示在form中
	public function findOrFail($id)
	{
		$sId = Admin::user()->sId;
		$url = $this->host."/storeMemberCards/get/{$id}?scKey=".$sId;
//		print_r($url);exit;
		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);
	
	    return static::newFromBuilder($data);
	}
	
	// 保存提交的form数据
	public function save(array $options = Array())
	{
		
	    $attributes = $this->getAttributes();

	    $userName = Admin::user()->name;
	    $now = date('Y-m-d H:i:s', time());
	    $sId = Admin::user()->sId;
	    $Common = new Common();
	    $storeInfo = $Common->getStroeInfo($sId);
	    
	    if (!isset($attributes['subNum'])){
	    	$attributes['subNum'] = count($attributes['sclParts']);
	    }
	    
	    $Store = new Store();
	    
	    // 根据是否有id判断添加还是更新
	    if (isset($attributes['smcId'])){
			$StoreMemberCards = new StoreMemberCards();
			$model = $StoreMemberCards->findOrFail($attributes['smcId']);
	    	if($attributes['subNum'] > $model->smcCanUseNum){
				$error = new MessageBag([
					'title'   => '保存失败',
					'message' => '最多可使用'.$model->smcCanUseNum.'次',
				]);		
				return back()->with(compact('error'));
			}
			
			$sclCode = $Common->createGuid();
			
			if (isset($attributes['sclParts'])){
				foreach($attributes['sclParts'] as $sclParts){
					$postData = array();
			    	$postData['scKey'] = $sId;
			    	$postData['sclCode'] = $sclCode;
			    	$postData['smcId'] = $attributes['smcId'];
			    	$postData['auCode'] = $attributes['auCode'];
			    	$postData['subNum'] = 1;
			    	$postData['sclParts'] = $sclParts;
			    	$postData['createUser'] = $userName;
			    	$postData['isGetMoney'] = $attributes['isGetMoney'];
					$url = $this->host."/storeMemberCards/subUseNum";
					
					$response = Curl::to($url)->withData($postData)->post();
					
					$Common->addStats($sId, 'useCard', 1,  $storeInfo['sCode']);
				}
			} else {
				$postData = array();
		    	$postData['scKey'] = $sId;
		    	$postData['sclCode'] = $sclCode;
		    	$postData['smcId'] = $attributes['smcId'];
		    	$postData['auCode'] = $attributes['auCode'];
		    	$postData['subNum'] = isset($attributes['subNum'])?$attributes['subNum']:1;
		    	$postData['createUser'] = $userName;
		    	$postData['isGetMoney'] = $attributes['isGetMoney'];
				$url = $this->host."/storeMemberCards/subUseNum";
				
				$response = Curl::to($url)->withData($postData)->post();
				
				$Common->addStats($sId, 'useCard', 1,  $storeInfo['sCode']);
			}
	    }else{
	    	$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);
		
		    return back()->with(compact('error'));
	    }

		

		$data = json_decode($response, true);
		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);
		
		    return back()->with(compact('error'));
		}
		if ($data['code'] == 0){
			// 抛出错误信息
			$error = new MessageBag([
		        'title'   => '保存失败',
		        'message' => $data['msg'],
		    ]);
		
		    return back()->with(compact('error'));
		}

		$sgInfo = DB::table('store_goods')->where('sgId', $attributes['sgId'])->first();
		$serviceMoney = $sgInfo->sgServiceMoney;
		
		// 是否包含服务费
		if ($sgInfo->sgIsIncludeService == 0){

			$Store = new Store();
			
			// 记录统计
			$statsUrl = $this->host."/statistics/dayAdd";
			$statsData = array();
			$statsData['scKey'] = $sId;
			$statsData['sdObjId'] = $storeInfo['sCode'];
			
			////////记录各个角色的钱包账户/////////////////////////////////////////
			$walletUrl = $this->host."/wallet/addTrade";
			$walletData = array();
			$walletData['wcusKey'] = $sId;
			$walletData['wtObj'] = 'cardService';
			$walletData['wtObjId'] = $sclCode;
			$walletData['createUser'] = $userName;

			// 是否已收到钱
			if ($attributes['isGetMoney']){
				$walletData['wtAbstract'] = '次卡服务费';
				$walletData['uId'] = $attributes['auCode'];
				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? $serviceMoney:$serviceMoney * $attributes['subNum'];
				Curl::to($walletUrl)->withData($walletData)->post();

				$walletData['wtAbstract'] = '提现';
				$walletData['uId'] = $attributes['auCode'];
				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? -1*$serviceMoney:-1*$serviceMoney * $attributes['subNum'];
				Curl::to($walletUrl)->withData($walletData)->post();
			}else{
				$walletData['wtAbstract'] = '次卡服务费代收';
				$walletData['uId'] = $storeInfo['sCode'];
				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? $serviceMoney:$serviceMoney * $attributes['subNum'];
				$walletData['wtCost'] = 0;
				$walletData['wtProfit'] = $attributes['sgShuiguangCard']==1 ? $serviceMoney:$serviceMoney * $attributes['subNum'];
				Curl::to($walletUrl)->withData($walletData)->post();
				
				$statsData['sdName'] = 'flowAccount';
				$statsData['sdValue'] = $walletData['wtChangedMoney'];
				Curl::to($statsUrl)->withData($statsData)->post();
				$statsData['sdName'] = 'profit';
				$statsData['sdValue'] = $walletData['wtProfit'];
				Curl::to($statsUrl)->withData($statsData)->post();
				
				// 记录店铺总收入
		    	$Store->addStoreIncrement($sId, 'sTotalCashFlow', $walletData['wtChangedMoney']);
			}
			
			$walletData['uId'] = $storeInfo['sCode'];
			$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? 2:2 * $attributes['subNum'];
			$walletData['wtAbstract'] = '次卡服务损耗费';
			$walletData['wtCost'] = 0;
			$walletData['wtProfit'] = $attributes['sgShuiguangCard']==1 ? 2:2 * $attributes['subNum'];;
			$data = Curl::to($walletUrl)->withData($walletData)->post();
			
			$statsData['sdName'] = 'flowAccount';
			$statsData['sdValue'] = $walletData['wtChangedMoney'];
			Curl::to($statsUrl)->withData($statsData)->post();
			$statsData['sdName'] = 'profit';
			$statsData['sdValue'] = $walletData['wtProfit'];
			Curl::to($statsUrl)->withData($statsData)->post();
			
			// 记录耗卡次数
			$statsData['sdName'] = 'cardUse';
			$statsData['sdValue'] = $attributes['subNum'];
			Curl::to($statsUrl)->withData($statsData)->post();

			// 记录店铺总收入
		    $Store->addStoreIncrement($sId, 'sTotalCashFlow', $walletData['wtChangedMoney']);
			////////记录各个角色的钱包账户/////////////////////////////////////////
		} else {
			// 已包含服务费，则由商家发放服务费

			// 记录统计
			$statsUrl = $this->host."/statistics/dayAdd";
			$statsData = array();
			$statsData['scKey'] = $sId;
			$statsData['sdObjId'] = $storeInfo['sCode'];
			
			////////记录各个角色的钱包账户/////////////////////////////////////////
			$walletUrl = $this->host."/wallet/addTrade";
			$walletData = array();
			$walletData['wcusKey'] = $sId;
			$walletData['wtObj'] = 'cardService';
			$walletData['wtObjId'] = $sclCode;
			$walletData['createUser'] = $userName;

			// 是否已收到钱
			if ($attributes['isGetMoney']){
				$walletData['wtAbstract'] = '次卡服务费';
				$walletData['uId'] = $attributes['auCode'];
				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? $serviceMoney:$serviceMoney * $attributes['subNum'];
				Curl::to($walletUrl)->withData($walletData)->post();
				
				$walletData['wtAbstract'] = '提现';
				$walletData['uId'] = $attributes['auCode'];
				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? -1*$serviceMoney:-1*$serviceMoney * $attributes['subNum'];
				Curl::to($walletUrl)->withData($walletData)->post();
				
				$walletData['wtAbstract'] = '次卡服务费发放';
				$walletData['uId'] = $storeInfo['sCode'];
				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? -1*$serviceMoney:-1*$serviceMoney * $attributes['subNum'];
				$walletData['wtCost'] = 0;
				$walletData['wtProfit'] = -1*$walletData['wtChangedMoney'];
				Curl::to($walletUrl)->withData($walletData)->post();

				$statsData['sdName'] = 'flowAccount';
				$statsData['sdValue'] = $walletData['wtChangedMoney'];
				Curl::to($statsUrl)->withData($statsData)->post();

				$statsData['sdName'] = 'profit';
				$statsData['sdValue'] = $walletData['wtProfit'];
				Curl::to($statsUrl)->withData($statsData)->post();
			} else {
//				$walletData['wtAbstract'] = '次卡服务费';
//				$walletData['uId'] = $attributes['auCode'];
//				$walletData['wtChangedMoney'] = $attributes['sgShuiguangCard']==1 ? $serviceMoney:$serviceMoney * $attributes['subNum'];
//
//				Curl::to($walletUrl)->withData($walletData)->post();
			}

			// 记录耗卡次数
			$statsData['sdName'] = 'cardUse';
			$statsData['sdValue'] = $attributes['subNum'];
			Curl::to($statsUrl)->withData($statsData)->post();
			////////记录各个角色的钱包账户/////////////////////////////////////////
		}

		return $this;
	}

	// 重写此方法，因为删除前要调用。不写则报错
	public function find($id){
		$this->muId = $id;
		return $this;
	}

	// 重写删除方法
	public function delete(){
		
		$attributes = $this->getAttributes();
		
		$remarkKey = config('services.extend.remarkKey');
		$remarkHost = config('services.extend.remarkHost');
		$url = $remarkHost.'/api/remark/delTag';
		
		// 请求外部数据
		$Functions = new Functions();
		$attributes['rcKey'] = $remarkKey;

		$data = $Functions->Post($url, $attributes);
		$data = json_decode($data, true);
		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);
		
		    return back()->with(compact('success'));
		}
		if ($data['code'] == 0){
			// 抛出错误信息
			$this->saving(function ($form) {
			
			    $error = new MessageBag([
			        'title'   => '保存失败',
			        'message' => $data['msg'],
			    ]);
			
			    return back()->with(compact('error'));
			});
		}else{
			// 抛出错误信息
			$this->saving(function ($form) {
			
			    $error = new MessageBag([
			        'title'   => '保存成功',
			        'message' => $data['msg'],
			    ]);
			
			    return back()->with(compact('success'));
			});
		}
		
		return $this;
	}
	
//	// 设置logo_url属性重写  提交信息时进入此方法
//	public function setLogoUrlAttribute($pictures)
//	{
////	    if (is_array($pictures)) {
////	        $this->attributes['pictures'] = json_encode($pictures);
////	    }
//	}
//	
//	// 获取logo_url属性重写 获取信息时进入此方法
//	public function getLogoUrlAttribute($pictures)
//	{
//		if (is_array($pictures)){
//			return $pictures;
//		}
//	    return json_decode($pictures, true);
//	}
}
